<template>
  <ContentWrap>
    <!-- 项目信息 -->
    <el-card class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <span>项目信息</span>
        </div>
      </template>
      <div v-if="currentProject">
        <div class="flex justify-between items-center mb-4">
          <div>
            <h3>{{ currentProject.name }}</h3>
            <p>{{ currentProject.remark }}</p>
          </div>
          <div>
            <el-button type="primary" @click="openProjectForm('update', currentProject.id)">
              编辑
            </el-button>
          </div>
        </div>
      </div>
      <div v-else>
        <el-empty description="请选择或创建一个项目" />
      </div>
    </el-card>

    <!-- 功能区域 -->
    <el-tabs v-model="activeTab" v-if="currentProject" @tab-click="handleTabClick">
      <!-- 原始需求 -->
      <el-tab-pane label="原始需求" name="original">
        <OriginalRequirementTab
          ref="originalTabRef"
          :project-id="projectId"
          @open-form="openOriginalForm"
          @decomposed="handleRequirementDecomposed"
        />
      </el-tab-pane>

      <!-- 分解需求 -->
      <el-tab-pane label="分解需求" name="cell">
        <el-row :gutter="20">
          <el-col :span="selectedCellId ? 12 : 24">
            <DecomposedRequirementTab
              ref="cellTabRef"
              :project-id="projectId"
              :selected-cell-id="selectedCellId"
              @select-cell="handleCellSelect"
              @extracted-table="handleTableExtracted"
              @decomposed="handleCellDecomposed"
              @open-form="openCellForm"
            />
          </el-col>
          <el-col :span="12" v-if="selectedCellId">
            <el-card>
              <template #header>
                <span>'{{ selectedCellName }}' 的详情</span>
              </template>
              <el-tabs>
                <el-tab-pane label="数据表">
                  <DataTableTab
                    ref="tableTabRef"
                    :project-id="projectId"
                    :cell-id="selectedCellId"
                    @open-form="openTableForm"
                    @view-fields="handleViewFields"
                  />
                </el-tab-pane>
                <el-tab-pane label="功能提示词">
                  <PromptTab
                    ref="promptTabRef"
                    :project-id="projectId"
                    :cell-id="selectedCellId"
                    @open-form="openPromptForm"
                    @generated-design="handleDesignGenerated"
                  />
                </el-tab-pane>
              </el-tabs>
            </el-card>
            <el-card v-if="selectedTableId" class="mt-4">
              <template #header>
                <span>'{{ selectedTableName }}' 的字段</span>
              </template>
              <FieldTab
                ref="fieldTabRef"
                :table-id="selectedTableId"
                @open-form="openFieldForm"
              />
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
  </ContentWrap>

  <!-- 表单弹窗 -->
  <ProjectForm ref="projectFormRef" @success="getProject" />
  <ProjectOriginalForm ref="originalFormRef" @success="refreshOriginalList" />
  <ProjectCellForm ref="cellFormRef" @success="refreshCellList" />
  <ProjectCellTableForm ref="tableFormRef" @success="refreshTableList" />
  <ProjectCellTableFieldForm ref="fieldFormRef" @success="refreshFieldList" />
  <ProjectCellPromptForm ref="promptFormRef" @success="refreshPromptList" />
</template>

<script setup lang="ts">
import { ref, onMounted, watch, toRef } from 'vue'
import { ProjectApi, ProjectVO } from '@/api/agent/project'
import { ProjectCellVO } from '@/api/agent/cell'
import { ProjectCellTableVO } from '@/api/agent/table'

// 表单
import ProjectForm from './ProjectForm.vue'
import ProjectOriginalForm from '../original/ProjectOriginalForm.vue'
import ProjectCellForm from '../cell/ProjectCellForm.vue'
import ProjectCellTableForm from '../table/ProjectCellTableForm.vue'
import ProjectCellTableFieldForm from '../field/ProjectCellTableFieldForm.vue'
import ProjectCellPromptForm from '../prompt/ProjectCellPromptForm.vue'

// 子组件
import OriginalRequirementTab from './manager/OriginalRequirementTab.vue'
import DecomposedRequirementTab from './manager/DecomposedRequirementTab.vue'
import DataTableTab from './manager/DataTableTab.vue'
import FieldTab from './manager/FieldTab.vue'
import PromptTab from './manager/PromptTab.vue'

/** 项目管理 */
defineOptions({ name: 'ProjectManager' })

const props = defineProps<{
  projectId: number
}>()

const projectIdRef = toRef(props, 'projectId')

// 全局状态
const activeTab = ref('original')
const currentProject = ref<ProjectVO>()

// 子组件引用
const originalTabRef = ref()
const cellTabRef = ref()
const tableTabRef = ref()
const fieldTabRef = ref()
const promptTabRef = ref()
const designTabRef = ref()

// 表单引用
const projectFormRef = ref()
const originalFormRef = ref()
const cellFormRef = ref()
const tableFormRef = ref()
const fieldFormRef = ref()
const promptFormRef = ref()

// 跨组件状态
const selectedCellId = ref<number | null>(null)
const selectedCellName = ref('')
const selectedTableId = ref<number | null>(null)
const selectedTableName = ref('')

/** 获取项目信息 */
const getProject = async () => {
  try {
    currentProject.value = await ProjectApi.getProject(props.projectId)
  } catch (error) {
    console.error('获取项目信息失败', error)
  }
}

/** 打开项目表单 */
const openProjectForm = (type: string, id?: number) => {
  projectFormRef.value.open(type, id)
}

// 表单打开逻辑
const openOriginalForm = (type: string, id?: number) => {
  originalFormRef.value.open(type, id, props.projectId)
}
const openCellForm = (type: string, id?: number) => {
  cellFormRef.value.open(type, id, props.projectId)
}
const openTableForm = (type: string, id?: number, cellId?: number) => {
  tableFormRef.value.open(type, id, cellId)
}
const openFieldForm = (type: string, id?: number, tableId?: number) => {
  fieldFormRef.value.open(type, id, tableId)
}
const openPromptForm = (type: string, id?: number, cellId?: number) => {
  promptFormRef.value.open(type, id, cellId)
}

// 列表刷新逻辑
const refreshOriginalList = () => originalTabRef.value?.getList()
const refreshCellList = () => cellTabRef.value?.getList()
const refreshTableList = () => tableTabRef.value?.getList()
const refreshFieldList = () => fieldTabRef.value?.getList()
const refreshPromptList = () => promptTabRef.value?.getList()
const refreshDesignList = () => designTabRef.value?.getFileList()

// 事件处理
const handleRequirementDecomposed = () => {
  activeTab.value = 'cell'
  refreshCellList()
}

const handleCellDecomposed = () => {
  refreshCellList()
}

const handleTableExtracted = () => {
  refreshTableList()
}

const handleDesignGenerated = () => {
  activeTab.value = 'design'
  refreshDesignList()
}

const handleCellSelect = (cell: ProjectCellVO) => {
  if (selectedCellId.value === cell.id) {
    selectedCellId.value = null
    selectedCellName.value = ''
  } else {
    selectedCellId.value = cell.id
    selectedCellName.value = cell.name
  }
  selectedTableId.value = null // Reset field view
}

const handleViewFields = (table: ProjectCellTableVO) => {
  selectedTableId.value = table.id
  selectedTableName.value = table.name
}

const handleTabClick = (tab: any) => {
  activeTab.value = tab.paneName
  if (activeTab.value !== 'cell') {
    selectedCellId.value = null
  }
  if (activeTab.value === 'design') {
    refreshDesignList()
  }
}

// 数据加载
const loadData = async () => {
  if (!props.projectId) return
  selectedCellId.value = null
  selectedTableId.value = null
  await getProject()
  await Promise.all([refreshOriginalList(), refreshCellList()])
}

onMounted(loadData)
watch(projectIdRef, loadData)
</script>
